<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>智慧教室 - By:康康</title>
		<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>

		<style>
			button {
				background-color: #0000AA;
				color: #FFFFFF;
				font-size: 1em;
				border-radius: 10px;
			}

			p {
				font-size: 1.5em;
			}

		</style>
	</head>

	<body>
		<p style="color: green; font-size: 1.5em;">台灯亮度：<span id="light">Loading...</span></p>

		<p>打开台灯：<button id="LightO">开灯</button></p>
		<p>关闭台灯：<button id="LightS">关灯</button></p>

		<p>增加亮度：<button id="LightU">+</button></p>
		<p>降低亮度：<button id="LightD">-</button></p>

		<script>
			function getQueryParam(param) {
				const url = window.location.href;
				const regex = new RegExp('[?&]' + param + '=([^&#]*)');
				const results = regex.exec(url);
				if (results === null) {
					return null;
				} else {
					return decodeURIComponent(results[1]) || '';
				}
			}

			const deviceId = getQueryParam('did') || 'kangkang1'; // 默认设备ID			
			const clientId = 'mqttjs_' + Math.random().toString(16).substr(2, 8);
			const host = 'ws://itmojun.com:8083/mqtt';
			const options = {
				keepalive: 60,
				clientId: clientId,
				protocolId: 'MQTT',
				protocolVersion: 4,
				clean: true,
				reconnectPeriod: 1000,
				connectTimeout: 30 * 1000,
				will: {
					topic: 'WillMsg',
					payload: 'Connection Closed abnormally..!',
					qos: 0,
					retain: false
				},
			};

			// 连接 MQTT 服务器
			const client = mqtt.connect(host, options);

			// 如果连接 MQTT 服务器成功
			client.on('connect', function() {
				console.log('Connected');

				// 订阅传感器主题
				client.subscribe(deviceId + '/state/+', function(err) {
					if (!err) {
						console.log('订阅主题: led');
					}
				});

			});

			// 接收服务器消息
			client.on('message', function(topic, message) {
				//console.log('Received Message: ' + topic + ' : ' + message.toString());

				if(topic === deviceId + '/state/light') {
					// 处理光照强度数据更新
					document.getElementById('light').innerText = '%' + message.toString() ;
				}				
			});

			// 按钮事件
			document.getElementById('LightO').addEventListener('click', function() {
				var message = 'o';  // 打开台灯

				client.publish(deviceId + '/cmd', message);
			});

			document.getElementById('LightS').addEventListener('click', function() {
				var message = 's';  // 关闭台灯
				
				client.publish(deviceId + '/cmd', message);
			});
	
			document.getElementById('LightU').addEventListener('click', function() {
				var message = 'u';  // 增加亮度

				client.publish(deviceId + '/cmd', message);
			});

			document.getElementById('LightD').addEventListener('click', function() {
				var message = 'd';  // 降低亮度
				
				client.publish(deviceId + '/cmd', message);
			});

		</script>
	</body>
</html>